package com.xjl.springbootpoi.controller;

import com.xjl.springbootpoi.resp.UserResp;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Desc:
 * @Author: xiejianlun
 * @Date: 2021/10/27 10:32
 */
@RestController
@RequestMapping("export")
public class ExportController {

    /**
     * 导出用户信息
     * @return
     */
    @RequestMapping(value = "user",method = RequestMethod.GET)
    public String exportUser(HttpServletResponse response) throws Exception {
        List<UserResp> list = new ArrayList<>();
        for(int i=0;i<10;i++){
            UserResp user = new UserResp();
            user.setId(i);
            user.setName("张三"+i);
            user.setSex("男");
            list.add(user);
        }

        Map<String, Object> resultmap = new HashMap<>();
        resultmap.put("list", list);
        resultmap.put("total",10);

        String fileName = "用户报表.xls";
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        String templateName = "USER.xlsx";
        File file = ResourceUtils.getFile(ExportController.class.getResource("/").getPath() + "excel/" + templateName);
        XLSTransformer transformer = new XLSTransformer();
        InputStream redfil = new FileInputStream(file);
        Workbook workbook1 = transformer.transformXLS(redfil, resultmap);
        workbook1.write(response.getOutputStream());
        return "SUCCESS";
    }
}
